package com.xingdata.jjxc.service;

import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

/**
 * 
 * 
 * 项目名称：JJXC_VPN 类名称：AppStatusService 类描述： 判断手机状态 创建人：JiangMin 创建时间：2015-6-17
 * 上午11:44:14 修改备注：
 * 
 * @version
 * 
 */
public class AppStatusService extends Service {
	private static final String TAG = "AppStatusService";
	private ActivityManager activityManager;
	private String packageName;
	private int inState = 0;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		activityManager = (ActivityManager) this
				.getSystemService(Context.ACTIVITY_SERVICE);
		packageName = this.getPackageName();
		new Thread() {
			public void run() {
				try {
					while (true) {
						Thread.sleep(1000);
						int state = isAppOnForeground();
						// 保证每次更改应用只进一次
						if (state != inState) {

							inState = state;
							int appState = 101;
							switch (inState) {
							// 正在运行
							case RunningAppProcessInfo.IMPORTANCE_FOREGROUND:
								Log.i(TAG, "正在运行");
								appState = 0;
								break;
							// 退出程序
							case RunningAppProcessInfo.IMPORTANCE_SERVICE:
								Log.i(TAG, "退出程序");
								appState = 9;
								break;
							// 后台
							case RunningAppProcessInfo.IMPORTANCE_BACKGROUND:
								Log.i(TAG, " 后台");
								appState = 1;
								break;
							default:
								break;
							}

//							if (BluetoothGattTools.getInstance()
//									.getUartService() != null
//									&& (appState == 0 || appState == 1)) {
//								HUDParameterEntity entity = new HUDParameterEntity();
//								entity.setNav_app_state(appState + "");
//								Consumer.getInstance()
//										.add(new MessageTask(
//												BluetoothGattTools
//														.getUartService(),
//												entity.toArrayList(entity),
//												Hud_Panid.ZXSendHudDataBeforTypeWithStart));
//							}

						}

					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		}.start();
		return super.onStartCommand(intent, flags, startId);
	}

	private int isAppOnForeground() {
		// Returns a list of application processes that are running on the
		// device
		List<RunningAppProcessInfo> appProcesses = activityManager
				.getRunningAppProcesses();
		if (appProcesses == null)
			return 0;
		for (RunningAppProcessInfo appProcess : appProcesses) {
			if (appProcess.processName.equals(packageName)) {
				return appProcess.importance;
			}
		}
		return 0;
	}
}
